using System;
using System.Collections.Generic;

namespace MMXSaveGameConverter
{
    internal sealed class DisposableStack : IDisposable
    {
        private readonly Stack<IDisposable> _stack = new Stack<IDisposable>();

        public T Add<T>(T item) where T : IDisposable
        {
            _stack.Push(item);
            return item;
        }

        public void Dispose()
        {
            List<Exception> exeptions = new List<Exception>();

            while (_stack.Count > 0)
                try
                {
                    IDisposable item = _stack.Pop();
                    if (item != null)
                        item.Dispose();
                }
                catch (Exception ex)
                {
                    exeptions.Add(ex);
                }

            if (exeptions.Count > 0)
                throw new AggregateException(exeptions);
        }
    }
}